package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.dao.DataDefineDao;
import com.cjack.frenchexcel.enumInfo.DataDefineTypeEnum;
import com.cjack.frenchexcel.exception.CommonException;
import com.cjack.frenchexcel.model.DataDefineModel;
import com.cjack.frenchexcel.table.DataDefineTable;
import com.cjack.frenchexcel.util.ModelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by root on 4/21/19.
 */
@Service
public class DataDefineService {

    @Autowired
    private DataDefineDao dao;

    public List< DataDefineModel> list( DataDefineTypeEnum type) {
        DataDefineTable condition = new DataDefineTable();
        condition.setType( type);
        Example< DataDefineTable> example = Example.of( condition);
        Sort sort = new Sort( Sort.Direction.DESC, "createTime");
        return ModelUtils.copyListModel( dao.findAll( example, sort), DataDefineModel.class);
    }

    public void add( DataDefineModel model) throws CommonException {
        DataDefineTable table = ModelUtils.copySignModel( model, DataDefineTable.class);
        dao.save( table);
    }

    public void del( String ids){
        List< DataDefineTable> tables = new ArrayList<>();
        String[] idArr = ids.split( ",");
        for( String id : idArr){
            DataDefineTable table = new DataDefineTable();
            table.setId( Long.valueOf( id));
            tables.add( table);
        }
        dao.deleteInBatch( tables);
    }

    public DataDefineTable get( Long id){
        return dao.getOne( id);
    }

    public DataDefineModel getByTypeAndKey( String type, String key){
        return ModelUtils.copySignModel( dao.findByTypeAndDataKey( DataDefineTypeEnum.valueOf( type), key), DataDefineModel.class);
    }
}
